/*
 * @Author: sdorein sdorein@163.com
 * @Date: 2024-07-25 17:51:23
 * @LastEditors: sdorein sdorein@163.com
 * @LastEditTime: 2024-07-26 09:24:45
 * @FilePath: \node-ts-project\server\wxupload.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const ci = require('miniprogram-ci');
const path = require('path');
const simpleGit = require('simple-git');
const git = simpleGit();

const project = new ci.Project({
  appid: 'wx15b099324a94e90e',
  type: 'miniProgram',
  projectPath: path.join(process.cwd(), 'dist/mp'), // 确保指向 miniprogram 目录
  privateKeyPath: path.join(process.cwd(), 'privatekey/private.wx70a595fc42f347f0.key'), // 修改此处
  ignores: ['node_modules/**/*'],
});

(async () => {
  try {
    // 获取当前 git HEAD 的短ID
    const shortCommitId = await new Promise((resolve, reject) => {
      git.revparse(['--short', 'HEAD'], (err, result) => {
        if (err) {
          console.error('Failed to retrieve short ID of HEAD:', err);
          reject(err);
          return;
        }
        resolve(result.trim());
      });
    });

    console.log('Short ID of HEAD:', shortCommitId);

    // 获取最新的提交信息
    const log = await git.log(['-1']);
    const commitMessage = log.latest.message;
    const commitHash = log.latest.hash;

    console.log('Latest commit message:', commitMessage);

    // 获取最新的标签信息
    const tags = await git.tags();
    const versionTag = tags.latest || '0.1.0';

    console.log('Latest version tag:', versionTag);

    // 构建版本号
    const shortCommitHash = commitHash.substring(0, 7);
    const version = `${versionTag}.${shortCommitId}`;
    const desc = commitMessage;

    console.log('上传版本号:', version);
    console.log('上传描述:', desc);

    // 执行上传操作
    console.log('开始上传...');
    const uploadResult = await ci.upload({
      project,
      version,
      desc,
      setting: {
        es6: true,
        minify: true,
      },
      onProgressUpdate: console.log,
    });

    console.log('上传结果:', uploadResult);
    process.exit();
  } catch (error) {
    console.error('上传失败:', error);
    process.exit(1);
  }
})();
